<template>
  <basic-container v-if="dialogVisible">
    <el-dialog :title="params.performanceName"
               :visible.sync="dialogVisible"
               append-to-body
               :width="width"
               :close-on-click-modal="false"
               :before-close="closeDialog">

      <el-form
        ref="form"
        :model="queryForm"
        label-width="120px"
        style="display: flex; flex-wrap: wrap"
      >
        <el-form-item style="width: 280px" label="媒体:">
          <el-select
            size="mini"
            v-model="queryForm.platform"
            placeholder="请选择"
            clearable
            @change="submitForm"
          >
            <el-option
              v-for="item in platformList"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="width: 280px" label="投放地区:">
          <el-select v-model="queryForm.nationList" size="mini" multiple clearable filterable placeholder="请选择" @change="submitForm">
            <el-option
              v-for="(item,index) in nationList"
              :key="index"
              :label="item.dictValue"
              :value="item.dictKey">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="更新时间:">
          <el-date-picker
            size="mini"
            v-model="queryForm.updateDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="submitForm"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <!--<avue-crud-->
      <!--  :option="option"-->
      <!--  :table-loading="loading"-->
      <!--  :data="data"-->
      <!--  :page.sync="page"-->
      <!--  @current-change="currentChange"-->
      <!--  @size-change="sizeChange"-->
      <!--  @on-load="onLoad"-->
      <!--&gt;-->
      <!--  <template slot-scope="{ row }" slot="ctr">-->
      <!--    <div>{{ row.ctr }}%</div>-->
      <!--  </template>-->
      <!--  <template slot-scope="{ row }" slot="cvr">-->
      <!--    <div>{{ row.cvr }}%</div>-->
      <!--  </template>-->
      <!--</avue-crud>-->

      <div class="curd-table">
        <div class="tab-header clearfix">
          <div class="tab-header-left">
          </div>
          <div class="tab-header-right">
          </div>
        </div>
        <div class="table-body">
          <el-table
            v-loading="loading"
            :data="data"
            border
            :header-cell-style="iHeaderCellStyle"
            style="width: 100%">
            <el-table-column
              v-for="item in renderTableColumn"
              :key="item.value"
              :prop="item.value"
              :label="item.label"
              :sortable="item.sortable"
              :width="item.width?item.width:''"
              :render-header="item.renderHeader">
              <!--<template v-slot="{row}" v-if="item.value==='prop'">-->
              <!--  <el-tooltip effect="dark" :content="row.prop" placement="left">-->
              <!--    <span class="over-flow">{{ row.prop }}</span>-->
              <!--  </el-tooltip>-->
              <!--</template>-->
              <template v-slot="{row}" v-if="item.value==='impressions'">
                <div>{{thousandSeparator(row.impressions)}}</div>
              </template>
              <template v-slot="{row}" v-else-if="item.value==='allExpend'">
                <div>{{thousandSeparator(row.allExpend)}}</div>
              </template>
              <template v-slot="{row}" v-else-if="item.value==='install'">
                <div>{{thousandSeparator(row.install)}}</div>
              </template>
              <template v-slot="{row}" v-else-if="item.value==='clicks'">
                <div>{{thousandSeparator(row.clicks)}}</div>
              </template>
              <template v-slot="{row}" v-else-if="item.value==='ctr'">
                {{ row.ctr }}%
              </template>
              <template v-slot="{row}" v-else-if="item.value==='cvr'">
                {{ row.cvr }}%
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="bottom-page clearfix">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.currentPage"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total">
          </el-pagination>
        </div>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getSysDictList} from '@/api/system/dict';
import {findObject} from "@/util/util";
import { getCreativeDetailList } from "@/api/offer/creativeperformance";
import Moment from "moment";
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";


export default {
  name: "creativePerformanceDetail",
  props: {
    width: String,
  },
  components: {
    CsDrawerContainer
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      dialogVisible: false,
      params: {},
      platformList: [],
      nationList:[],

      queryForm: {
        platform: null,
        beginDate: null,
        endDate: null,
        nationList: [],
        updateDateRange: [],
      },
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      data: [],
      option: {
        calcHeight: 30,
        tip: false,
        border: true,
        index: false,
        selection: false,
        menu: false,
        menuLeft: false,
        refreshBtn: false,
        columnBtn: false,
        addBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "更新时间",
            prop: "reportDate",
          },
          {
            label: "媒体",
            prop: "platform",
            multiple: true,
            dataType: 'string',
            dicData: [],
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            searchMultiple: true,
          },
          {
            label: "投放地区",
            prop: "country",
            dataType: 'string',
            multiple: true,
            dicData: [],
            props: {
              label: "dictValue",
              value: "dictKey",
            },
          },
          {
            label: "花费",
            prop: "allExpend",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "曝光",
            prop: "impressions",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            width:120,
            sortable: 'custom',
          },
          {
            label: "点击",
            prop: "clicks",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "CTR",
            prop: "ctr",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "安装",
            prop: "install",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "CVR",
            prop: "cvr",
            rules: [
              {
                required: true,
                message: "请输入CVR",
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
        ],
      },
      // 显隐已选择项
      tableColumnValue: ["reportDate","platform","country","allExpend","impressions","clicks","ctr","install","cvr",],
      // 显隐配置项
      tableColumnData: [
        {
          label: "更新时间",
          value: "reportDate",
        },
        {
          label: "媒体",
          value: "platform",
        },
        {
          label: "投放地区",
          value: "country",
        },
        {
          label: "花费",
          value: "allExpend",
        },
        {
          label: "曝光",
          value: "impressions",
        },
        {
          label: "点击",
          value: "clicks",
        },
        {
          label: "CTR",
          value: "ctr",
        },
        {
          label: "安装",
          value: "install",
        },
        {
          label: "CVR",
          value: "cvr",
        },
      ],
      defaultTableColumnData: [
        {
          label: "更新时间",
          value: "reportDate",
        },
        {
          label: "媒体",
          value: "platform",
        },
        {
          label: "投放地区",
          value: "country",
        },
        {
          label: "花费",
          value: "allExpend",
        },
        {
          label: "曝光",
          value: "impressions",
        },
        {
          label: "点击",
          value: "clicks",
        },
        {
          label: "CTR",
          value: "ctr",
        },
        {
          label: "安装",
          value: "install",
        },
        {
          label: "CVR",
          value: "cvr",
        },
      ],
      defaultTableColumnValue: ["reportDate","platform","country","allExpend","impressions","clicks","ctr","install","cvr",]
    }
  },
  computed: {
    renderTableColumn() {
      return this.tableColumnData.filter(item => this.tableColumnValue.includes(item.value))
    }
  },
  created(){
    this.onLoad(this.page)
    getSysDictList("platforms,nation").then(map => {
      this.platformList = map['platforms'];
      this.nationList = map['nation'];
      let column = findObject(this.option.column,'platform','prop');
      if(column != null) {
        column.dicData = this.platformList;
      }
      column = findObject(this.option.column,'country','prop');
      if(column != null) {
        column.dicData = this.nationList;
      }
    });
  },
  methods: {
    async showDialog(params) {
      this.dialogVisible = true;
      this.params = {...params};
      this.buildSearch();
      const sameColumn = this.defaultTableColumnValue.filter(item=>this.params.tableColumnValue.includes(item))
      this.tableColumnData =[...this.defaultTableColumnData,...this.params.eventData]
      this.tableColumnValue=['reportDate',...sameColumn,...this.params.selectedEventData.split(',')]
      await this.onLoad(this.page)
    },
    closeDialog() {
      this.dialogVisible = false;
      this.page = {
        pageSize: 10,
          currentPage: 1,
          total: 0,
      }
    },

    buildSearch() {
      let query = {
        platform: this.queryForm.platform,
      };
      if (this.queryForm.updateDateRange != null && this.queryForm.updateDateRange.length == 2) {
        query.beginDate = this.queryForm.updateDateRange[0];
        query.endDate = this.queryForm.updateDateRange[1];
      }
      query.country = this.queryForm.nationList.join(',')
      this.query = query;
    },
    submitForm() {
      this.buildSearch();
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getCreativeDetailList(
        this.page.currentPage,
        this.page.pageSize,
        Object.assign({}, {creativeId: this.params.creativeId}, this.query, {eventData: this.params.selectedEventData}),
      ).then((res) => {
        let data = res.data.data;
        this.page.total = data.total;
        let resultList = data.records;
        for (let i = 0; i < resultList.length; i++) {
          if(resultList[i].country != null && resultList[i].country != '') {
            let countryList = resultList[i].country.split(',');
            let set = new Set();
            countryList.forEach(c=>{
              set.add(c);
            });
            resultList[i].country = Array.from(set).join(',');
          }
          resultList[i].reportDate = Moment(resultList[i].reportDate).format("yyyy-MM-DD");
        }
        this.data = resultList;
        this.loading = false;
      });
    },
    iHeaderCellStyle() {
      return {
        color: '#101010',
        backgroundColor: '#F2F2F2'
      }
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.onLoad(this.page)
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.onLoad(this.page)
    },
    thousandSeparator(num){
      let s = num.toString();
      let div = s.indexOf('.');
      let sign = (num < 0)?'-':'';
      let intPart = (div == -1)?s:s.substring(0,div);
      let dotPart = (div == -1)?'':s.substring(div);
      let finalIntPart = '';
      while(intPart.length > 3) {
        finalIntPart = ',' + intPart.substring(intPart.length - 3) + finalIntPart;
        intPart = intPart.substring(0,intPart.length-3);
      }
      return sign + intPart + finalIntPart + dotPart;
    },
  }
}

</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: flex-end;
}

::v-deep .el-card__header {
  border-bottom: unset;
}

.curd-table {
  .tab-header {
    font-size: 14px;
    margin-bottom: 15px;

    .tab-header-left {
      float: left;

      & > * {
        margin-right: 15px;
      }
    }

    .tab-header-right {
      float: right;
    }
  }

  .bottom-page {
    margin-top: 15px;

    .el-pagination {
      float: right;
    }
  }
}

.clearfix:after {
  content: "";
  display: block;
  clear: both;
}
</style>
